package com.ciwong.epaper.modules.epaper.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.CorrectLinesRelut;
import com.ciwong.epaper.modules.epaper.bean.CorrectLinesWordsRelut;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.i.RecordInterFace;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.widget.PlayStateDubView;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.evaluate.SpeechTextView;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.bean.Word;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.widget.BuyServiceDialog;

import java.util.List;

/**
 * Created by byou
 */

public class DubVideoRecordingAdapter extends
        BaseQuickAdapter<Sentence, DubVideoRecordingAdapter.BookDeskViewHolder> {

    private RecordInterFace mRecordInterFace;

    private Activity mContext;

    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    public DubVideoRecordingAdapter(Activity mContext, int layoutResId,
                                    @Nullable List<Sentence> data, RecordInterFace mRecordInterFace,
                                    boolean serviceExpired) {
        super(layoutResId, data);
        this.mRecordInterFace = mRecordInterFace;
        this.mContext = mContext;
        this.serviceExpired = serviceExpired;
    }

    @Override
    protected void convert(BookDeskViewHolder helper, Sentence sentence) {
        helper.bindData(mContext, sentence, mRecordInterFace, serviceExpired);
    }

    @Override
    public void onBindViewHolder(BookDeskViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        int viewType = holder.getItemViewType();

        switch (viewType) {
            case 0:
                if (holder.tv_NO != null) {
                    holder.tv_NO.setText((position + 1) + "/" + mData.size());
                }
                break;
        }

    }

    public class BookDeskViewHolder extends BaseViewHolder {
        public Sentence mSentence;

        public TextView tv_NO;

        public SpeechTextView item_speech_tv;

        public RelativeLayout score_rel;

        public TextView score_text, see_score_text;

        public ImageView score_fuhao;

        public TextView tv_translate;

        public RelativeLayout rel_play_recored_dubing;

        public PlayStateView play_record_iocn;

        public ImageView play_iocn;

        public PlayStateDubView play_dubing_iocn;

        public BookDeskViewHolder(View view) {
            super(view);
        }

        public void bindData(Context mContext, Sentence sentence,
                             final RecordInterFace mRecordInterFace, boolean serviceExpired) {
            mSentence = sentence;
            tv_NO = getView(R.id.tv_NO);
            item_speech_tv = getView(R.id.item_speech_tv);
            score_rel = getView(R.id.score_rel);
            score_text = getView(R.id.score_text);
            score_fuhao = getView(R.id.score_fuhao);
            see_score_text = getView(R.id.see_score_text);
            tv_translate = getView(R.id.tv_translate);
            rel_play_recored_dubing = getView(R.id.rel_play_recored_dubing);
            play_record_iocn = getView(R.id.play_record_iocn);
            play_iocn = getView(R.id.play_iocn);
            play_dubing_iocn = getView(R.id.play_dubing_iocn);
            if (sentence != null) {
                if (sentence.hasGrade()) {
                    score_rel.setVisibility(View.VISIBLE);
                    setScoreResult(mContext, sentence.getScore(), score_rel,
                            score_text, see_score_text, score_fuhao, serviceExpired);
                    showSentenceResult(mContext, item_speech_tv,
                            sentence.getAser(), sentence, false, serviceExpired);
                } else {
                    score_rel.setVisibility(View.GONE);
                    item_speech_tv.setText(sentence.getText());
                    if (sentence.isSelect()) {
                        item_speech_tv.setTextColor(mContext.getResources()
                                .getColor(R.color.black));
                    } else {
                        item_speech_tv.setTextColor(mContext.getResources()
                                .getColor(R.color.default_dub_text_color));
                    }
                }
                if (sentence.isSelect()) {
                    rel_play_recored_dubing.setVisibility(View.VISIBLE);
                } else {
                    rel_play_recored_dubing.setVisibility(View.GONE);
                }
                tv_translate.setText(sentence.getTranslate());
                play_record_iocn.setTimeAndPlayBtnState(
                        (long) sentence.getDuration() + 400,
                        PlayStateView.RECORD_STATUE);
                play_dubing_iocn.setTimeAndPlayBtnState(
                        (long) sentence.getDuration() + 400,
                        PlayStateView.PLAY_STATUE);
                play_record_iocn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mRecordInterFace != null) {
                            mRecordInterFace.startRecordView();
                        }
                    }
                });
                play_dubing_iocn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mRecordInterFace != null) {
                            mRecordInterFace.playRecordView();
                        }
                    }
                });
            }
        }
    }

    /**
     * 设置答案
     *
     * @param mContext
     * @param score
     * @param score_rel
     * @param score_text
     * @param score_fuhao
     */
    public void setScoreResult(Context mContext, int score,
                               RelativeLayout score_rel, TextView score_text, TextView see_score_text,
                               ImageView score_fuhao, boolean serviceExpired) {
        if (serviceExpired) {
            int color;
            int image;
            if (score < SpeechUtils.TOTAL_SCORE_1) {
                color = R.color.score_red;
                image = R.mipmap.score_red_rep;
            } else if (score < SpeechUtils.TOTAL_SCORE_3) {
                color = R.color.score_yellow;
                image = R.mipmap.score_orange_rep;
            } else {
                color = R.color.score_green_word;
                image = R.mipmap.score_green_rep;
            }
            score_rel.setVisibility(View.VISIBLE);
            score_text.setText(score + "");
            score_text.setTextColor(mContext.getResources().getColor(color));
            score_fuhao.setImageResource(image);
            score_fuhao.setVisibility(View.VISIBLE);
            see_score_text.setVisibility(View.GONE);
        } else {
            score_rel.setVisibility(View.VISIBLE);
            score_text.setText("已提交");
            score_text.setTextSize(16);
            score_text.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
            score_fuhao.setVisibility(View.GONE);
            String text = "查看分数";
            SpannableString spannableString = new SpannableString(text);
            spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
            see_score_text.setText(spannableString);
            see_score_text.setOnClickListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    setBuyServiceDialog();
                }
            });
            see_score_text.setVisibility(View.VISIBLE);
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(mContext);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(mContext, R.string.go_back, mContext.getResources().getString(R.string.resource_center));
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    /**
     * 设置评分结果
     *
     * @param er       评分后的单词
     * @param sentence 句子
     * @param isFill   true=选段背诵
     */
    public static void showSentenceResult(Context mContext,
                                          SpeechTextView textView, CorrectLinesRelut er, Sentence sentence,
                                          boolean isFill, boolean serviceExpired) {
        sentence.setHasGrade(true);
        final int score = (int) Math.floor(SpeechUtils.scoreOptimize(er.getScore()));
        sentence.setScore(score);
        sentence.setTextColor(
                mContext.getResources().getColor(R.color.repeat_read_gray));
        sentence.setAser(er);
        if (serviceExpired) {
            List<CorrectLinesWordsRelut> gradeWords = er.getWords();
            List<WordDetail> words = sentence.getWordDetails();

            int index = 0;
            String sample = SpeechUtils.replaceAsSpace(er.getSample());
            String sentenceText = SpeechUtils.replaceAsSpace(
                    SpeechUtils.replaceEvaluateText(sentence.getText()));
            int gradeWordIndexStart = 0;
            int gradeWordIndex = 0;
            for (int i = 0; i < gradeWords.size(); i++) {
                CorrectLinesWordsRelut gradeWord = gradeWords.get(i);
                if (gradeWord.getType() == 4) {
                    continue;
                }
                String gradeWordText = gradeWord.getText().trim();
                // 修改与2016/09/29 对单词也要做字符过滤 不然去子字符串的时候会报错
                gradeWordText = SpeechUtils.replaceAsSpace(gradeWordText);

                if (gradeWordIndex != -1) {
                    gradeWordIndex = sample.indexOf(gradeWordText, gradeWordIndex);
                    // 说明去子集的时候报错了 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理 所以要索引要减去1
                    if (gradeWordIndex == -1) {
                        gradeWordIndex -= 1;
                        gradeWordIndex = sample.indexOf(gradeWordText,
                                gradeWordIndex);
                    }
                    gradeWordIndexStart = gradeWordIndex;
                }
                if (gradeWordIndex != -1) {
                    gradeWordIndex += gradeWordText.length() + 1;
                }
                index = 0;
                int wIndexStart = 0;
                int wIndex = 0;
                while (true) {
                    if (index >= words.size()) {
                        break;
                    }
                    WordDetail w = words.get(index);
                    String wStr = w.getText().trim();
                    if (wIndex != -1) {
                        wIndex = sentenceText.indexOf(wStr, wIndex);
                        wIndexStart = wIndex;
                    }
                    if (wIndex != -1) {
                        wIndex += wStr.length() + 1;
                    }
                    // 匹配规则修改2016/09/29 开始位置一样 或者结束位置一样 by young
                    // 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理
                    boolean isMatch = (gradeWordIndex != -1 && wIndex != -1
                            && gradeWordIndex == wIndex)
                            || (gradeWordIndex != -1 && wIndex != -1
                            && gradeWordIndexStart == wIndexStart);
                    // 匹配规则修改2016/09/29 相等或者是子集都表示相同by young
                    // 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理 所以反过来包括也可以
                    if ((isMatch && SpeechUtils.replace(w.getText())
                            .equals(gradeWord.getText()))
                            || (isMatch && SpeechUtils.replace(w.getText())
                            .contains(wStr))
                            || (isMatch && wStr
                            .contains(SpeechUtils.replace(w.getText())))) {
                        w.setScore(gradeWord.getScore());
                        int color;
                        if (gradeWord.getScore() < SpeechUtils.ONE_SCORE_2) {
                            color = R.color.me_item_name_sub_txt_color;

                        } else if (gradeWord.getScore() < SpeechUtils.ONE_SCORE_2) {
                            color = R.color.score_red;

                        } else if (gradeWord.getScore() < SpeechUtils.ONE_SCORE_4) {
                            color = R.color.score_yellow;

                        } else {
                            color = R.color.score_green_word;

                        }
                        w.setColor(mContext.getResources().getColor(color));
                        index++;
                        continue;
                    }
                    index++;

                }
            }

            textView.setScoreTextSize(mContext.getResources().getDimensionPixelSize(
                    R.dimen.speech_text_view_result_text_size));
            textView.setFillblank(isFill);
            textView.setSentence(sentence, false);
            textView.setTextColor(
                    mContext.getResources().getColor(R.color.repeat_read_gray));

            // 将人名设置为黑色
            try {
                int[] indexArray = SpeechUtils
                        .isMatchPersonName(sentence.getText());
                if (indexArray != null) {
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                            mContext.getResources()
                                    .getColor(R.color.default_text_color));
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                            textView.getText());
                    spannableStringBuilder.setSpan(foregroundColorSpan,
                            indexArray[0], indexArray[1] - 1,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    // 将翻译设为黑色。
                    int[] translateArray = SpeechUtils
                            .isMatchPersonName(sentence.getText());
                    if (translateArray != null) {
                        spannableStringBuilder.setSpan(foregroundColorSpan,
                                translateArray[0] - 2, translateArray[1] - 1,
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    }

                    textView.setText(spannableStringBuilder);
                } else {
                    int[] translateArray = SpeechUtils
                            .isMatchPersonName(sentence.getText());
                    if (translateArray != null) {
                        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                                mContext.getResources()
                                        .getColor(R.color.default_text_color));
                        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                                textView.getText());
                        spannableStringBuilder.setSpan(foregroundColorSpan,
                                translateArray[0], translateArray[1],
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        textView.setText(spannableStringBuilder);
                    }
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        } else {
            sentence.setTextColor(
                    mContext.getResources().getColor(R.color.black));
            textView.setScoreTextSize(mContext.getResources().getDimensionPixelSize(
                    R.dimen.speech_text_view_result_text_size));
            textView.setFillblank(isFill);
            textView.setSentence(sentence, false);
            textView.setTextColor(
                    mContext.getResources().getColor(R.color.black));
        }

    }

}
